package com.lanou.musicproject.activity;


import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.lanou.musicproject.R;
import com.lanou.musicproject.adapter.LyricAdapter;
import com.lanou.musicproject.base.BaseActivity;
import com.lanou.musicproject.base.BaseApplication;
import com.lanou.musicproject.bean.MyMusicList;
import com.lanou.musicproject.bean.MySong;
import com.lanou.musicproject.event.MyEvent;
import com.lanou.musicproject.lrc.LyricDownloadManager;
import com.lanou.musicproject.lrc.LyricLoadHelper;
import com.lanou.musicproject.lrc.LyricSentence;
import com.lanou.musicproject.lrcsc.LyricAdaptersrc;
import com.lanou.musicproject.lrcsc.LyricLoadHelpersrc;
import com.lanou.musicproject.lrcsc.LyricSentencesrc;
import com.lanou.musicproject.musicservice.MusicInterface;
import com.lanou.musicproject.musicservice.MusicService;
import com.lanou.musicproject.tools.MusicPlayPopupWindow;
import com.lanou.musicproject.tools.Time;
import com.squareup.picasso.Picasso;


import java.io.File;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;


/**
 * Created by ztq on 15/10/26.
 */
public class MusicPlayActivity extends BaseActivity implements View.OnClickListener, SeekBar.OnSeekBarChangeListener {
    private ArrayList<MySong> mysong;//本地歌曲实体类
    private ArrayList<MyMusicList> myMusicLists;//网络歌曲实体类
    private MyServiceConn conn;
    private Intent intent;
    private static Context mContext;
    private static TextView start_time, end_time;
    private RelativeLayout musicplayRL;

    MusicPlayPopupWindow playPopupWindow;
    private static Button listBtn, downloadBtn;
    private static ImageView playIv, repeatIv, formerBtn, nextBtn;
    private LyricAdapter lyricAdapter;
    private LyricAdaptersrc lyricAdaptersrc;
    private TextView lyric_empty;
    private static SeekBar seekbar;
    private static MusicInterface mi;
    private static TextView titleTv;
    private int color;


    private static ImageView albumIv, change;
    private ListView lrc_list;

    private int changeDrawable[] = {R.drawable.bt_playpage_button_lyric_press, R.drawable.bt_playpage_button_lyric_normal};
    private int i;
    private static FrameLayout player_frame_content;

    private static LyricLoadHelper mLyricLoadHelper;
    private static LyricLoadHelpersrc mLyricLoadHelpersrc;

    public static int PLAYMODE;
    public static final int PLAYLOCAL = 0;
    public static final int PLAYONLINE = 1;

    public static final int RANDOM = 2;
    public static final int INORDER = 3;
    public static final int SINGLE = 4;
    public static int REPEATMODE = INORDER;


    private TextView mLrcEmptyView;
    private boolean mIsLyricDownloading;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_musicplay);
        mContext = this;
        playIv = (ImageView) findViewById(R.id.playIv);
        nextBtn = (ImageView) findViewById(R.id.nextBtn);
        formerBtn = (ImageView) findViewById(R.id.formerBtn);
        seekbar = (SeekBar) findViewById(R.id.seekbar);
        titleTv = (TextView) findViewById(R.id.titleTv);
        albumIv = (ImageView) findViewById(R.id.albumIv);
        start_time = (TextView) findViewById(R.id.start_time);
        end_time = (TextView) findViewById(R.id.end_time);
        repeatIv = (ImageView) findViewById(R.id.repeatIv);
        lrc_list = (ListView) findViewById(R.id.lrc_list);
        change = (ImageView) findViewById(R.id.change);
        lyric_empty = (TextView) findViewById(R.id.lyric_empty);
        listBtn = (Button) findViewById(R.id.listBtn);
        musicplayRL = (RelativeLayout) findViewById(R.id.musicplayRL);

        player_frame_content = (FrameLayout) findViewById(R.id.player_frame_content);
        player_frame_content.setVisibility(View.INVISIBLE);


        intent = new Intent(this, MusicService.class);
        startService(intent);
        conn = new MyServiceConn();
        bindService(intent, conn, BIND_AUTO_CREATE);


        lyricAdapter = new LyricAdapter(this);
        mLyricLoadHelper = new LyricLoadHelper();
        lrc_list.setEmptyView(lyric_empty);
        lrc_list.setAdapter(lyricAdapter);
        mLyricLoadHelper.setLyricListener(mLyricListener);

        lyricAdaptersrc = new LyricAdaptersrc(this);
        mLyricLoadHelpersrc = new LyricLoadHelpersrc();
        mLyricLoadHelpersrc.setLyricListener(mLyricListeners);
        lrc_list.setAdapter(lyricAdaptersrc);


        playIv.setOnClickListener(this);
        formerBtn.setOnClickListener(this);
        nextBtn.setOnClickListener(this);
        listBtn.setOnClickListener(this);
//        downloadBtn.setOnClickListener(this);
        repeatIv.setOnClickListener(this);
        change.setOnClickListener(this);

        lyric_empty.setOnClickListener(this);
        seekbar.setOnSeekBarChangeListener(this);

        //注册颜色广播
        IntentFilter rgbFilter = new IntentFilter();
        rgbFilter.addAction("rgbAction");
        registerReceiver(rgbReceiver, rgbFilter);

    }

    private LyricLoadHelper.LyricListener mLyricListener = new LyricLoadHelper.LyricListener() {

        @Override
        public void onLyricLoaded(List<LyricSentence> lyricSentences, int index) {
            // Log.i(TAG, "onLyricLoaded");
            if (lyricSentences != null) {

                lyricAdapter.setLyric(lyricSentences);
                lyricAdapter.setCurrentSentenceIndex(index);
                lyricAdapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onLyricSentenceChanged(int indexOfCurSentence) {

            lyricAdapter.setCurrentSentenceIndex(indexOfCurSentence);
            lyricAdapter.notifyDataSetChanged();
            lrc_list.smoothScrollToPositionFromTop(indexOfCurSentence,
                    lrc_list.getHeight() / 2, 500);
        }
    };
    private LyricLoadHelpersrc.LyricListener mLyricListeners = new LyricLoadHelpersrc.LyricListener() {
        @Override
        public void onLyricLoaded(List<LyricSentencesrc> lyricSentencess, int indexOfCurSentence) {
            if (lyricSentencess != null) {

                lyricAdaptersrc.setLyric(lyricSentencess);
                lyricAdaptersrc.setCurrentSentenceIndex(indexOfCurSentence);
                lyricAdaptersrc.notifyDataSetChanged();
            }
        }

        @Override
        public void onLyricSentenceChanged(int indexOfCurSentence) {
            lyricAdaptersrc.setCurrentSentenceIndex(indexOfCurSentence);
            lyricAdaptersrc.notifyDataSetChanged();
            lrc_list.smoothScrollToPositionFromTop(indexOfCurSentence,
                    lrc_list.getHeight() / 2, 500);
        }
    };

    public static LyricLoadHelper getHelpter() {
        return mLyricLoadHelper;
    }

    public static LyricLoadHelpersrc getHelpers(){
        return mLyricLoadHelpersrc;
    }


    /**
     * 判断前一首后一首是网络还是本地
     **/
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.playIv:

                if (mi.getIsPlay()) {
                    mi.pause();
                } else if (mi.getDuration() > mi.getProgress()) {
                    mi.continuePlay();
                }

                break;
            case R.id.formerBtn:

                if (PLAYMODE == PLAYONLINE) {
                    mi.former();
                } else if (PLAYMODE == PLAYLOCAL) {
                    mi.localFormer();
                }


                break;
            case R.id.nextBtn:


                if (PLAYMODE == PLAYONLINE) {

                    mi.next();


                } else if (PLAYMODE == PLAYLOCAL) {
                    mi.localNext();
                }


                break;
            //列表
            case R.id.listBtn:
                myMusicLists = mi.musicLists();

                Log.i("========", myMusicLists + "");

                playPopupWindow = new MusicPlayPopupWindow(mContext, myMusicLists, itemOnClick);
                //显示窗口
                playPopupWindow.showAtLocation(MusicPlayActivity.this.findViewById(R.id.listBtn), Gravity.BOTTOM | Gravity.CLIP_VERTICAL, 0, 0); //设置layout在PopupWindow中显示的位置

                break;
            case R.id.repeatIv:

                //循环方法
                if (REPEATMODE == INORDER) {
                    //从顺序播放变成随机播放
                    //设置随机播放的状态
                    repeatIv.setBackgroundResource(R.mipmap.random);

                    REPEATMODE = RANDOM;
                    Toast.makeText(mContext, "随机播放模式", Toast.LENGTH_SHORT).show();

                    //eventbus发送数据
                    int what = RANDOM;
                    EventBus.getDefault().post(new MyEvent.PlayEvent(what));

                } else if (REPEATMODE == RANDOM) {
                    // 随机播放变成单曲播放
                    //设置单曲播放的状态
                    repeatIv.setBackgroundResource(R.mipmap.single);
                    Toast.makeText(mContext, "单曲循环模式", Toast.LENGTH_SHORT).show();
                    REPEATMODE = SINGLE;

                    //eventbus发送数据通知单曲播放
                    //结束时不会自动下一首
                    int what = SINGLE;
                    EventBus.getDefault().post(new MyEvent.PlayEvent(what));

                } else if (REPEATMODE == SINGLE) {
                    //从单曲播放变成顺序播放
                    //设置顺序播放的状态
                    REPEATMODE = INORDER;
                    repeatIv.setBackgroundResource(R.mipmap.order);
                    Toast.makeText(mContext, "顺序播放模式", Toast.LENGTH_SHORT).show();

                    //eventbus发送数据
                    int what = INORDER;
                    EventBus.getDefault().post(new MyEvent.PlayEvent(what));
                }

                break;
            case R.id.change:
                if (i == 0) {
                    i++;
                    player_frame_content.setVisibility(View.VISIBLE);
                    albumIv.setVisibility(View.GONE);
                    change.setImageResource(changeDrawable[0]);
                } else {
                    i = 0;
                    player_frame_content.setVisibility(View.GONE);
                    albumIv.setVisibility(View.VISIBLE);
                    change.setImageResource(changeDrawable[1]);
                }

                break;
            case R.id.lyric_empty:

                        mLyricLoadHelper.loadLyric(mi.getlrcdownload());


                    mLyricLoadHelper.loadLyric(mi.getlrcdownload());


                break;
        }
    }

    //为弹出窗口实现监听类
    private View.OnClickListener itemOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            playPopupWindow.dismiss();
            switch (v.getId()) {
                case R.id.popup_listView:

                    break;
            }
        }
    };

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        //根据拖动的进度改变音乐播放进度
        int progress = seekBar.getProgress();
        //改变播放进度
        mi.seekTo(progress);
    }

    public static Handler handler = new Handler() {


        public void handleMessage(android.os.Message msgplay) {

            Bundle bundle = msgplay.getData();
            int duration = bundle.getInt("duration");
            int currentPostition = bundle.getInt("currentPosition");
            //刷新进度条的进度
            if (seekbar != null) {
                seekbar.setMax(duration);
                seekbar.setProgress(currentPostition);
                start_time.setText(Time.formatTime((long) currentPostition));
                end_time.setText(Time.formatTime((long) duration));
                mLyricLoadHelper.notifyTime((long) currentPostition);
                mLyricLoadHelpersrc.notifyTime((long)currentPostition);

                init();
            }


        }
    };

    //设置按钮图片 歌名
    private static void init() {
        if (mi != null) {
            if (mi.getIsPlay()) {
                playIv.setImageResource(R.mipmap.player_btn_pause);
            } else {
                playIv.setImageResource(R.mipmap.player_btn_play);
            }
            titleTv.setText(mi.getName());

            if (mi.getPlayer_Singer_Image() != null) {
                Picasso.with(mContext).load(mi.getPlayer_Singer_Image()).into(albumIv);
            }
        }
    }

    //广播的接收
    private BroadcastReceiver rgbReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    color = intent.getIntExtra("rgb", 0);
                    Log.i("broadCastRe", color + "");
                    musicplayRL.setBackgroundColor(color);

                    //clear
                    lyricAdapter.setLyric(null);
                    lyricAdapter.notifyDataSetChanged();

                    //add
                    mLyricLoadHelper.loadLyric(mi.getlrcdownload());
                    mLyricLoadHelpersrc.loadLyric(mi.getlrcdownload());
        }
    };

    //在线播放
    public static void playIv(ArrayList<MyMusicList> lists, int position) {


        PLAYMODE = PLAYONLINE;

        if (mi != null) {
            mi.play(lists, position);
        }

        //eventbus向服务中传递数据
        int what = PLAYONLINE;
        EventBus.getDefault().post(new MyEvent.PlayEvent(what));

    }

    //本地播放
    public static void playIv(List<MySong> mysong, int position) {


        PLAYMODE = PLAYLOCAL;
        if (mi != null) {
            mi.playLocal(mysong, position);
            mLyricLoadHelper.loadLyric(mi.getlrcdownload());
        }

        //eventbus向服务中传递数据
        int what = PLAYLOCAL;
        EventBus.getDefault().post(new MyEvent.PlayEvent(what));
    }

    class MyServiceConn implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mi = (MusicInterface) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(conn);
        unregisterReceiver(rgbReceiver);
    }


}